<template>
  <div class="search-div">
    <el-form label-width="70px" size="small">
      <el-row>
        <el-col :span="6">
          <el-form-item label="商品名称">
            <el-input
              v-model.trim="queryDto.productName"
              style="width: 100%"
              clearable
              placeholder="请输入要检索的商品名称"
            >
              <template #prefix>
                <el-icon class="el-input__icon">
                  <search />
                </el-icon>
              </template>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分类">
            <SelectCategory :searchCategoryIdList="searchCategoryIdList" @handleChange="handleChangeCategory"  />
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="品牌">
            <el-select
              v-model="queryDto.brandName"
              placeholder="选择品牌"
              size="small"
              style="width: 160px"
            >
              <el-option
                v-for="item in categoryBrandList"
                :key="item.id"
                :label="item.brandName"
                :value="item.brandName"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="销售状态">
            <el-select
              v-model="queryDto.status"
              placeholder="选择销售状态"
              size="small"
            >
              <el-option label="全部" :value="null" />
              <el-option label="未上架" :value="0" />
              <el-option label="已上架" :value="1" />
              <el-option label="自主下架" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="审核状态">
            <el-select
              v-model="queryDto.auditStatus"
              placeholder="选择审核状态"
              size="small"
            >
              <el-option label="全部" :value="null" />
              <el-option label="未审核" :value="0" />
              <el-option label="通过" :value="1" />
              <el-option label="未通过" :value="2" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row style="display:flex">
        <el-button type="primary" size="small" @click="fetchData">
          搜索
        </el-button>
        <el-button size="small" @click="resetData">重置</el-button>
      </el-row>
    </el-form>
  </div>

  <div class="tools-div">
    <el-button type="success" size="small" @click="addShow">添 加</el-button>
  </div>

  <el-table :data="list" style="width: 100%">
    <el-table-column label="序号" #default="scope" width="60" align="center">
      {{ (pageParams.page - 1) * pageParams.limit + scope.$index + 1 }}
    </el-table-column>
    <el-table-column label="商品轮播图" width="150" #default="scope" align="center">
      <el-carousel :interval="3000" arrow="never" indicator-position="none">
        <el-carousel-item v-for="(item, index) in scope.row.sliderUrls" :key="index">
          <el-image
            :src="item"
            class="product_banner"
            fit="cover"
          />
        </el-carousel-item>
      </el-carousel>
    </el-table-column>
    <el-table-column prop="productName" label="商品名称" width="200" />
    <el-table-column label="所属分类" #default="scope" align="center">
      {{scope.row.category1}} / {{scope.row.category2}} / {{ scope.row.category3}}
    </el-table-column>
    <el-table-column prop="brandName" label="品牌" width="80" align="center" />
    <el-table-column prop="unitName" label="计量单位" width="80" align="center" />
    <el-table-column prop="status" label="状态" #default="scope" width="125" align="center">
      <el-tag v-if="scope.row.status === 0" type="warning">未上架</el-tag>
      <el-tag v-else :type="scope.row.status === 1 ? 'success' : 'danger' ">
        {{ scope.row.status === 1 ? "已上架" : "自主下架" }}
      </el-tag>
    </el-table-column>
    <el-table-column prop="auditStatus" label="审核状态" #default="scope" width="125" align="center">
      <el-tag v-if="scope.row.auditStatus === 0" type="warning">未审核</el-tag>
      <el-tag v-else :type="scope.row.auditStatus === 1 ? 'success' : 'danger' ">
        {{ scope.row.auditStatus === 1 ? "通过" : "未通过" }}
      </el-tag>
    </el-table-column>
    <el-table-column label="操作" align="center" width="200" #default="scope">
      <el-button type="primary" size="small" @click="editShow(scope.row.id)" class="ctrl-btn">
        修改
      </el-button>
      <el-button type="danger" size="small" @click="removeById(scope.row.id)" class="ctrl-btn" :disabled="scope.row.status === 1">
        删除
      </el-button>
      <el-button
        v-if="scope.row.auditStatus === 0 || scope.row.auditStatus === 2"
        type="success" size="small" class="ctrl-btn"
        @click="audit(scope.row.id)"
      >审核
      </el-button>
      <el-button
        v-if=" scope.row.auditStatus === 1 && (scope.row.status === 0 || scope.row.status === 2)"
        type="warning" size="small" class="ctrl-btn"
        @click="updateStatus(+scope.row.id, 1)"
      >上架
      </el-button>
      <el-button
        v-if="scope.row.auditStatus === 1 && scope.row.status === 1"
        type="info" plain size="small" class="ctrl-btn"
        @click="updateStatus(+scope.row.id, 2)"
      >下架
      </el-button>
    </el-table-column>
  </el-table>

  <el-pagination
    v-model:current-page="pageParams.page"
    v-model:page-size="pageParams.limit"
    :page-sizes="[10, 20, 50, 100]"
    layout="total, sizes, prev, pager, next"
    :total="total"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />

  <el-dialog v-model="dialogVisible" title="添加或修改" width="80%" :before-close="closeForm">
    <ProductForm
      :defaultForm="product"
      :dialogVisible="dialogVisible"
      :productId="productId"
      @submitForm="submitForm"
      @closeForm="closeForm" />
  </el-dialog>

  <el-dialog v-model="dialogAuditVisible" title="商品审核" width="80%" :before-close="cancelAudit">
    <Audit
      :product="auditProduct"
      :audit-file="auditFiles"
      :auditMessage="auditMessage"
      @updateAuditStatus="updateAuditStatus"
      @cancelAudit="cancelAudit"
    />
  </el-dialog>
</template>

<script setup>
import { onMounted, ref } from "vue";
import productApi from "@/api/product/product.js";
import { getBrandByCategoryId } from "@/api/product/categoryBrand.js";
import { ElMessage, ElMessageBox } from "element-plus";
import { debounce, deepClone } from "@/utils";
import Audit from "@/views/product/product/components/audit.vue";
import ProductForm from "@/views/product/product/components/productForm.vue";
import SelectCategory from "@/components/SelectCategory/selectCategory.vue";

// ------------------------分页列表查询 开始 -----------------------
// 传给子组件选择好的分类ID
const searchCategoryIdList = ref([])
// 选择分类
const handleChangeCategory = (lastId, arr) => {
  // 选择好分类后，查询属于该分类的品牌
  if (lastId) getBrand(lastId);
  queryDto.value.brandName = null
  searchCategoryIdList.value = arr
};
// 从数据库获取品牌数据
const getBrand = async id => {
  const { data } = await getBrandByCategoryId(id);
  categoryBrandList.value = data;
};
// 定义品牌的数据模型
const categoryBrandList = ref([]);

const defaultQuery = {
  productName: null,
  brandName: null,
  category1Id: null,
  category2Id: null,
  category3Id: null,
  status: null,
  auditStatus: null
};
// 选中的数据模型
const queryDto = ref(deepClone(defaultQuery));

//分页数据
const pageParamsForm = {
  page: 1, // 页码
  limit: 10 // 每页记录数
};
const pageParams = ref(pageParamsForm);

// 表格数据模型
const list = ref([]);
// 总记录数数据模型
const total = ref(0);
//页面变化
const handleSizeChange = size => {
  pageParams.value.limit = size;
  fetchData();
};
const handleCurrentChange = number => {
  pageParams.value.page = number;
  fetchData();
};

//重置查询条件
const resetData = debounce(() => {
  queryDto.value = deepClone(defaultQuery);
  searchCategoryIdList.value = [];
  fetchData();
}, 500);
// ------------------------分页列表查询 结束 ---------------------

// 钩子函数
onMounted(async () => {
  await fetchData();
});

// 分页列表查询方法
const fetchData = debounce(async () => {

  // 处理三级分类的id
  queryDto.value.category1Id = null
  queryDto.value.category2Id = null
  queryDto.value.category3Id = null
  if (searchCategoryIdList.value.length === 1) {
    queryDto.value.category1Id = searchCategoryIdList.value[0];
  }
  if (searchCategoryIdList.value.length === 2) {
    queryDto.value.category1Id = searchCategoryIdList.value[0];
    queryDto.value.category2Id = searchCategoryIdList.value[1];
  }
  if (searchCategoryIdList.value.length === 3) {
    queryDto.value.category1Id = searchCategoryIdList.value[0];
    queryDto.value.category2Id = searchCategoryIdList.value[1];
    queryDto.value.category3Id = searchCategoryIdList.value[2];
  }
  // 请求后端接口
  const { data } = await productApi.page(pageParams.value.page, pageParams.value.limit, queryDto.value);
  // 将响应结果数据设置给对应的属性模型
  list.value = data.records.map(product => {
    //处理图片
    if(product.sliderUrls) {
      product.sliderUrls = product.sliderUrls.split(",")
    }
    return product
  })
  total.value = data.total;
}, 200);

// --------------------- 添加或修改 ------------------------
// 控制对话框是否展示的数据模型
const dialogVisible = ref(false);

// 表单数据模型
const defaultForm = {
  id: null,
  name: null,
  brandId: null,
  categories: [],
  unitName: null,
  specValueId: null,
  productDetails: {},
  productSkuList: []
};
const product = ref(deepClone(defaultForm));
const productId = ref(null)

// 提交表单
const submitForm = async productDto => {
  const result = await productApi.saveProduct(productDto)
  if (result.code === 250) {
    ElMessage.success("操作成功");
    dialogVisible.value = false
  } else {
    ElMessage.error(result.message);
  }
  await fetchData();
}

// 关闭表单弹窗
const closeForm = () => {
  dialogVisible.value = false
  product.value = deepClone(defaultForm)
}

//进入添加
const addShow = () => {
  productId.value = null
  dialogVisible.value = true;
};

//进入修改
const editShow = id => {
  productId.value = id
  dialogVisible.value = true;
};

//删除
const removeById = async id => {
  ElMessageBox.confirm("此操作将永久删除该记录, 是否继续?", "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(async () => {
      await productApi.removeProduct(id);
      ElMessage.success("删除成功");
      await fetchData();
    })
    .catch(() => {
      ElMessage.info("取消删除");
    });
};

/* --------------------- 审核开始 -----------------------*/
// 审批弹窗切换
const dialogAuditVisible = ref(false);
// 审核商品的数据
const auditProduct = ref({})
let auditMessage = ref("审核通过");
// 图片预览
let auditFiles = ref({
  sliderUrls: [],  // banner
  imageUrls: []  // 审核用的商品详情图
});
// 开始审核
const audit = async id => {
  const { data } = await productApi.getProductInfoById(id);
  auditProduct.value = data;
  //处理图片
  if (auditProduct.value.productDetails.sliderUrls) {
    auditFiles.value.sliderUrls = auditProduct.value.productDetails.sliderUrls.split(",");
  }
  if (auditProduct.value.productDetails.imageUrls) {
    auditFiles.value.imageUrls = auditProduct.value.productDetails.imageUrls.split(",");
  }
  dialogAuditVisible.value = true;
};

// 审核商品
const updateAuditStatus = async data => {
  const result = await productApi.checkProduct(data);
  if (result.code === 260) {
    ElMessage.success("操作成功");
    dialogAuditVisible.value = false;
    await fetchData();
  } else {
    ElMessage.error(result.message);
  }
};

// 取消审核
const cancelAudit = () => {
  auditMessage.value = "审核通过";
  dialogAuditVisible.value = false;
};
/* --------------------- 审核结束  -----------------------*/

// 商品上下架操作
const updateStatus = (id, status) => {
  ElMessageBox.confirm("请确认商品信息无异，再进行此操作", "商品上下架", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  }).then(async () => {
    const result = await productApi.onSale({ id, status });
    dialogAuditVisible.value = false;
    ElMessage.success(result.message);
    await fetchData();
  });
};

</script>

<style scoped>

.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}

.avatar-uploader .avatar {
  width: 50px;
  height: 50px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  text-align: center;
}

.ctrl-btn {
  padding: 5px;
  margin-left: 5px;
}

:deep(.el-carousel__container) {
  overflow: hidden;
  width: 60px;
  height: 60px;
  margin: 0 auto;
  text-align: center;
}
</style>
